package com.fruit.auth.service.impl;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fruit.auth.dao.UserDao;
import com.fruit.auth.dao.UserRoleDao;
import com.fruit.auth.model.Privilege;
import com.fruit.auth.model.Role;
import com.fruit.auth.model.User;
import com.fruit.auth.model.UserRole;
import com.fruit.auth.service.PrivilegeService;
import com.fruit.auth.service.UserService;
import com.fruit.dao.BaseDao;
import com.fruit.service.impl.BaseServiceImpl;
import com.fruit.util.Algorithm;
import com.fruit.util.SecurityUtil;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService
{
	@Resource(name="userDao")
	private UserDao userDao;
	
	@Resource(name="userRoleDao")
	private UserRoleDao userRoleDao;
	
	@Resource(name="privilegeService")
	private PrivilegeService privilegeService;
	
	@Override
	public User login(String username, String password)
	{
		User user=userDao.login(username);
		if(user==null)
			return null;
		String pwd=SecurityUtil.messageDigest(password, Algorithm.SHA_256);
		if(user.getPassword().equals(pwd))
		{
			return user;
		}
		return null;
	}

	public void authUserPrivileges(User user)
	{
		List<Role> roles=userRoleDao.findUserRoles(user);
		for(Role role:roles)
		{
			if(role.getRoleCode().equals(Role.ROLE_ADMIN))
			{
				
				user.setAdmin(true);
				break;
			}
		}
		//如果该用户不是超级管理员则加载其权限，访问资源时需要经过授权;如果是管理员则不用加载权限，直接放行访问一切资源
		if(!user.isAdmin())
		{
			List<Privilege> authPrivileges=privilegeService.findPrivilegesForUser(user.getId());
			user.calcPrivilege(authPrivileges);
		}
	}
	
	public boolean checkUsername(String username)
	{
		return userDao.checkUsernameIsExists(username);
	}
	
	public void saveUser(User u)
	{
		u.setPassword(SecurityUtil.messageDigest(u.getPassword(), Algorithm.SHA_256));
		u.setCreateTime(Calendar.getInstance().getTime());
		userDao.saveEntity(u);
	}
	
	public void saveUserRoles(User user,List<Serializable> roleIds)
	{
		userRoleDao.saveUserRoles(user, roleIds);
	}
	
	public void updateUserRoles(User user,List<Serializable> roleIds)
	{
		userRoleDao.updateUserRoles(user, roleIds);
	}

	@Override
	public void saveUserRole(UserRole userRole)
	{
		userRoleDao.saveUserRole(userRole);
		
	}

	public void deleteUsers(String userIdsStr)
	{
		userDao.deleteUsers(userIdsStr);
	}
	
	@Override
	public BaseDao<User> getEntityDao()
	{
		return userDao;
	}
	
	public List<Role> findUserRoles(User user)
	{
		return userRoleDao.findUserRoles(user);
	}
	
}
